import request from '../request'
import getOpenID from '../getOpenID'
import cache, {removeCache} from '../cache'


// 获取地址列表信息
export const getAddress = cache('addressList', async () => {
  const {openid} = await getOpenID()
  const res = await request('/address/', {
    openid
  })
  return res
})

// 添加地址信息
export const addAddress = async (data) => {
  const {openid} = await getOpenID()

  const res = await request('/address/', {
    ...data,
    user: openid,
    openid
  }, 'POST')

  removeCache('addressList')
  return res
}

// 删除地址信息
export const deleteAddress = async (id) => {
  const {openid} = await getOpenID()

  const res = await request(`/address/${id}/`, {
    openid
  }, 'DELETE')

  removeCache('addressList')
  return res
}

// 更新地址信息
export const editAddress = async (data) => {
  const {openid} = await getOpenID()

  const res = await request(`/address/${data.id}/`, {
    ...data,
    user: openid,
    openid
  }, 'PUT')

  removeCache('addressList')
  return res
}

// 获取地址详情
export const getAddressDetail = async (id) => {
  const addressList = await getAddress()
  return addressList.find(item => item.id === id)
}